/**
 * jims
 */
package com.jims.master.modules.finance.service;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.PatVisitDao;
import com.jims.master.modules.finance.dao.InpAcctDetailDao;
import com.jims.master.modules.finance.dao.InpAcctMasterDao;
import com.jims.master.modules.finance.dao.InpAcctMoneyDao;
import com.jims.master.modules.finance.dao.PatPrepaymentDao;
import com.jims.master.modules.finance.entity.InpAcctDetail;
import com.jims.master.modules.finance.entity.InpAcctMaster;
import com.jims.master.modules.finance.entity.InpAcctMoney;
import com.jims.master.modules.finance.entity.PatPrepayment;
import com.jims.master.modules.med.dao.MedicalCardConsumeDetailDao;
import com.jims.master.modules.med.dao.MedicalCardConsumeMasterDao;
import com.jims.master.modules.med.dao.MedicalCardMasterDao;
import com.jims.master.modules.med.entity.MedicalCardConsumeDetail;
import com.jims.master.modules.med.entity.MedicalCardConsumeMaster;
import com.jims.master.modules.med.entity.MedicalCardMaster;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.NumberToCN;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 病人预交金记录Service
 * @author 赵宁
 * @version 2017-03-28
 */
@Service
@Transactional(readOnly = true)
public class PatPrepaymentService extends CrudService<PatPrepaymentDao, PatPrepayment> {
    @Autowired
    private InpAcctMasterDao inpAcctMasterDao;
	@Autowired
	private InpAcctMoneyDao inpAcctMoneyDao;
	@Autowired
	private InpAcctDetailDao inpAcctDetailDao;
	@Autowired
	private PatVisitDao patVisitDao;
	@Autowired
	private CompanyDao companyDao;
	@Autowired
	private MedicalCardConsumeMasterDao medicalCardConsumeMasterDao;
	@Autowired
	private MedicalCardConsumeDetailDao medicalCardConsumeDetailDao;
	@Autowired
	private MedicalCardMasterDao medicalCardMasterDao;




	public PatPrepayment get(String id) {
		return super.get(id);
	}
	
	public List<PatPrepayment> findList(PatPrepayment patPrepayment) {
		return super.findList(patPrepayment);
	}
	
	public Page<PatPrepayment> findPage(Page<PatPrepayment> page, PatPrepayment patPrepayment) {
		return super.findPage(page, patPrepayment);
	}
	/**
	 * 一卡通缴纳预交金
	 * @param patPrepayment
	 * @return
	 * @author CTQ
	 * @date 2017-07-19 20:26:26
	 */
	@Transactional(readOnly = false)
	public int saveOneCardSolution(PatPrepayment patPrepayment) {
		patPrepayment.setRcptNo(NumberUtils.getVisitPreIn(patPrepayment.getVisitId()));
		patPrepayment.setRefundedId(null);
		patPrepayment.setRefundedUser(null);
		patPrepayment.setUpdateBy(null);
		patPrepayment.setUpdateDate(null);
		patPrepayment.setAcctNo(null);
        patPrepayment.setType("1");
		patPrepayment.preInsert();
		handleMedicalCard(patPrepayment,patPrepayment.getOneCardNo());
		patPrepayment.updateOrgId();
		return dao.insert(patPrepayment);
	}

	/**
	 * 作废预交金
	 * @param patPrepayment
	 * @return
	 * @update by CTQ AT 2017-07-20 11:02:31
	 */
	@Transactional(readOnly = false)
	public int deletePatPre(PatPrepayment patPrepayment) {
		patPrepayment.setAmount(0-patPrepayment.getAmount());
		/**判断是否是一卡通缴纳预交金**/
		if (patPrepayment.getPayWay().equals("3")){
				handleMedicalCard(patPrepayment,null);
		}
		patVisitDao.updatePrepayments(patPrepayment.getVisitId(),patPrepayment.getAmount());
		patPrepayment.setType("2");
		return dao.delete(patPrepayment);
	}


	/**
	 * 预交金退费-现金退费/一卡通退费
	 * @param patPrepayment
	 * @return
	 * @author CTQ
	 * @date 2017-07-20 11:31:40
	 */
	@Transactional(readOnly = false)
	public StringData returnPatPre(PatPrepayment patPrepayment) {
		StringData data = new StringData();
		int num = 0;
		patPrepayment.setAmount(0-patPrepayment.getAmount());
		/**判断是否是一卡通缴纳预交金，一卡通缴纳预交金需要退费到一卡通**/
		if (patPrepayment.getPayWay().equals("3")){
			handleMedicalCard(patPrepayment,null);
		}
		patVisitDao.updatePrepayments(patPrepayment.getVisitId(),patPrepayment.getAmount());
		/**插入退款负记录信息**/
		PatPrepayment prepayment = dao.get(patPrepayment.getId());
		prepayment.setId("");
		prepayment.preInsert();
		prepayment.updateOrgId();
		prepayment.setAmount(0-prepayment.getAmount());
		prepayment.setType("4");
		prepayment.setRcptNo(NumberUtils.getVisitPreIn(prepayment.getVisitId()));//预交金序号
		dao.insert(prepayment);
		/**更新退款原记录信息**/
		patPrepayment.setType("1");//需要退款的正记录，不修改状态
		patPrepayment.setRefundedId(prepayment.getRcptNo());//正记录退款号=负记录rcpt_no
		patPrepayment.setRefundedUser(UserUtils.getUser().getId());
		num = dao.delete(patPrepayment);
		if(num>0){
			data.setCode("success");
			data.setData("预交金退款成功！");
		}else {
			data.setCode("error");
			data.setData("预交金退款失败！");
		}
		return data;
	}

	/**
	 * 一卡通预交金缴费/作废/退款公用方法
	 * @param patPrepayment
	 * @author CTQ
	 * @date 2017-07-20 10:52:13
	 */
	@Transactional(readOnly = false)
	public void handleMedicalCard(PatPrepayment patPrepayment,String cardNo){
		if (StringUtils.isBlank(cardNo)){
			/**根据病人信息及预交金信息，查询出一卡通卡号**/
			MedicalCardConsumeMaster card  = new MedicalCardConsumeMaster();
			card.setPatientId(patPrepayment.getPatientId());
			card.setItemClass("预交金");
			card.setClinicItemDictId(patPrepayment.getId());
			card.setRcptNo(patPrepayment.getRcptNo());
			card.setFeeFlag("0");
			card.updateOrgId();
			MedicalCardConsumeMaster mcc = medicalCardConsumeMasterDao.findByParam(card);
			if (mcc!=null) {
				cardNo=mcc.getCardNo();
			}
		}

			/**扣除一卡通缴纳预交金费用**/
			MedicalCardConsumeMaster medicalCardConsumeMaster = new MedicalCardConsumeMaster();
			medicalCardConsumeMaster.setPatientId(patPrepayment.getPatientId());
			medicalCardConsumeMaster.setCardNo(cardNo);
			medicalCardConsumeMaster.setConsumeMoney(patPrepayment.getAmount());
			medicalCardConsumeMaster.setRcptNo(patPrepayment.getRcptNo());
			medicalCardConsumeMaster.setClinicItemDictId(patPrepayment.getId());
			medicalCardConsumeMaster.setItemClass("预交金");
			if (patPrepayment.getAmount()>0){
				medicalCardConsumeMaster.setFeeFlag("0");//消费
			}else {
				medicalCardConsumeMaster.setFeeFlag("1");//退费
			}
			medicalCardConsumeMaster.updateOrgId();
			medicalCardConsumeMaster.preInsert();
			medicalCardConsumeMasterDao.insert(medicalCardConsumeMaster);
			/**插入一卡通消费明细表**/
			MedicalCardConsumeDetail medicalCardConsumeDetail = new MedicalCardConsumeDetail();
			medicalCardConsumeDetail.setMasterId(medicalCardConsumeMaster.getId());
			medicalCardConsumeDetail.setConsumeMoney(patPrepayment.getAmount());
			medicalCardConsumeDetail.setPriceId(patPrepayment.getId());
			medicalCardConsumeDetail.setItemName("预交金");
			medicalCardConsumeDetail.setItemClass("预交金");
			medicalCardConsumeDetail.setItemPrice(patPrepayment.getAmount());
			medicalCardConsumeDetail.setAmount(1);
			medicalCardConsumeDetail.updateOrgId();
			medicalCardConsumeDetail.preInsert();
			medicalCardConsumeDetailDao.insert(medicalCardConsumeDetail);

			/**根据一卡通卡号，更新一卡通余额信息**/
			MedicalCardMaster medicalCardMaster = new MedicalCardMaster();
			medicalCardMaster.setCardNo(cardNo);
			MedicalCardMaster med=medicalCardMasterDao.findByCardNo(medicalCardMaster);
			med.setBalance(med.getBalance()+medicalCardMaster.getDeposit()-patPrepayment.getAmount());
			medicalCardMasterDao.updateBalance(med);
	}

	/**
	 * 查询预交金余额
	 * @param wardCode
	 * @param orgId
	 * @param name
	 * @return
	 * @author 赵宁
	 */
    public Page<BaseDto> getPaymentBlance(Page<BaseDto> page,String wardCode,String orgId,String name){
		 return page.setList(dao.getPaymentBlance(wardCode,name,orgId));
	}
	/**
	 * 查询预交金记录--出院结算
	 * @param patPrepayment
	 * @return
	 * @author 赵宁
	 */
	public PatPrepayment findPrepayments(PatPrepayment patPrepayment){
       return dao.findPayments(patPrepayment);
	}

	/**
	 * 缴纳预交金
	 * @return
	 */
	@Transactional(readOnly = false)
	public int savePatPrepayment(PatPrepayment patPrepayment){
		int num = 0;
		patPrepayment.setRcptNo(NumberUtils.getVisitPreIn(patPrepayment.getVisitId()));//预交金序号
		patPrepayment.preInsert();
		patPrepayment.updateOrgId();
		patPrepayment.setRefundedUser("");
		patPrepayment.setType("1");
		dao.insert(patPrepayment);
		num= patVisitDao.updatePrepayments(patPrepayment.getVisitId(),patPrepayment.getAmount());
		return num;
	}

	/**
	 * 预交金查询总费用
	 * @param inpAcctMaster
	 * @return
	 * @author 赵宁
	 */
	public  InpAcctMaster getPrepayment(InpAcctMaster inpAcctMaster){
        return dao.getPrepayments(inpAcctMaster);
	}

	/**
	 * 查询预交金支付方式统计
	 * @param inpAcctMaster
	 * @return
	 * @author 赵宁
	 */
	public List<InpAcctMoney> getPayWay(InpAcctMaster inpAcctMaster){
		return dao.getPayWay(inpAcctMaster);
	}

	/**
	 * 预交金结账--查询预交金数据
	 * @return
	 * @author 赵宁
	 */
	public List<PatPrepayment> getPaymentsByAcct(InpAcctMaster inpAcctMaster){
		return  dao.getPaymentsByAcct(inpAcctMaster);
	}

	/**
	 * 预交金结账保存
	 * @param inpAcctMaster
	 * @return
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public String confirmAcct(InpAcctMaster inpAcctMaster){
		int code=0;
		String acctNo = inpAcctMasterDao.getMaxAcctNo();
		if(StringUtils.isNotBlank(acctNo)&& acctNo!=null){
			int no= Integer.parseInt(acctNo)+1;
			acctNo = String.valueOf(no);
		}else{
			acctNo=""+28000;
		}
		InpAcctMaster acctMaster=dao.getPrepayments(inpAcctMaster);
		acctMaster.setAcctNo(acctNo);
		acctMaster.setChargesAmount(acctMaster.getSumAmount());
		acctMaster.setInvalidNum("0");
		acctMaster.setStartDate(inpAcctMaster.getStartDate());
		acctMaster.setEndDate(inpAcctMaster.getEndDate());
		acctMaster.setOrgId(inpAcctMaster.getOrgId());
		acctMaster.setAcctType("1");
		acctMaster.preInsert();
		code=inpAcctMasterDao.insert(acctMaster);
		List<InpAcctMoney> inpAcctMoneys=dao.getPayWay(inpAcctMaster);
		if(inpAcctMoneys!=null && inpAcctMoneys.size()>0){
			for(int i=0;i<inpAcctMoneys.size();i++){
				InpAcctMoney inpAcctMoney = inpAcctMoneys.get(i);
				inpAcctMoney.setAcctNo(acctNo);
				inpAcctMoney.setAcctId(acctMaster.getId());
				inpAcctMoney.setOrgId(acctMaster.getOrgId());
				inpAcctMoney.preInsert();
				inpAcctMoneyDao.insert(inpAcctMoney);
			}
		}
		List<PatPrepayment> patPrepayments=dao.getPaymentsByAcct(inpAcctMaster);
		if(patPrepayments!=null && patPrepayments.size()>0){
			for(int j=0;j<patPrepayments.size();j++){
                PatPrepayment patPrepayment= patPrepayments.get(j);
				InpAcctDetail inpAcctDetail=new InpAcctDetail();
				inpAcctDetail.setAcctNo(acctNo);
				inpAcctDetail.setAcctId(acctMaster.getId());
				inpAcctDetail.setOrgId(acctMaster.getOrgId());
				if(patPrepayment.getType().equals("1")){
					inpAcctDetail.setCosts(patPrepayment.getAmount());
					inpAcctDetail.setIncome(patPrepayment.getAmount());
				}else if(patPrepayment.getType().equals("2")){
					inpAcctDetail.setCosts(-patPrepayment.getAmount());
					inpAcctDetail.setIncome(-patPrepayment.getAmount());
				}
				inpAcctDetail.setSubjCode("Z");
				inpAcctDetail.preInsert();
				inpAcctDetailDao.insert(inpAcctDetail);
			}
		}
        dao.updatePrepayment(acctMaster);
		return acctNo;
	}


	/**
	 * 护理端催补预交金
	 * @param patPrepayment
	 * @return
	 * @author CTQ
	 */
	public List<BaseDto> searchWaitPrePayment(PatPrepayment patPrepayment){
		return dao.searchWaitPrePayment(patPrepayment);
	}

	/**
	 * 获取预交金催单打印路径
	 * @param patPrepayment
	 * @return
	 * @author CTQ
	 */
	public String reminderPrint(PatPrepayment patPrepayment){
		User user = UserUtils.getUser();

		Map map = new HashMap();
		List<BaseDto> list = dao.reminderPrint(patPrepayment);

		String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/reminderPrint.jasper", map, list, "reminderPrint");
		return  printPath;
	}
    /**
     * 获取预交金打印路径
     * @param patPrepayment
     * @return
     * @author yangfuda
     */
    public String prepaidPaymentPrint(PatPrepayment patPrepayment){
        User user = UserUtils.getUser();
        Map map = new HashMap();
        BaseDto baseDto = dao.prepaidPaymentPrint(patPrepayment);

/*        String visitNo = (String)baseDto.get("visitNo");//住院号
        String pmiName = (String)baseDto.get("pmiName");//患者姓名
        String sex = (String)baseDto.get("sex");//性别
        String deptName = (String)baseDto.get("deptName");//住院科室
        String chargeType = (String)baseDto.get("chargeType");//费别
        String amount = (String)baseDto.get("amount");//金额
        String payWay = (String)baseDto.get("payWay");//付款方式
        String piName = (String)baseDto.get("piName");//收款员
        String orgName = (String)baseDto.get("orgName");//医院名称*/
        String createDate = DateFormatUtils.format(baseDto.getAsDate("createDate","yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss");//收款时间
       // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String dateString = formatter.format(createDate);
        baseDto.put("createDate",createDate);
        String amountBig = NumberToCN.number2CNMontrayUnit(new BigDecimal(baseDto.getAsDouble("amount")));
        baseDto.put("amountBig",amountBig);
/*        map.put("visitNo",visitNo);
        map.put("pmiName",pmiName);
        map.put("sex",sex);
        map.put("deptName",deptName);
        map.put("chargeType",chargeType);*/
        DecimalFormat df   = new DecimalFormat("######0.00");
        baseDto.put("amount","￥"+df.format(baseDto.getAsDouble("amount")));
        baseDto.put("amountBig","￥"+amountBig);
      /*  map.put("payWay",payWay);
        map.put("piName",piName);
        map.put("createDate",createDate);*/
        map.put("orgNameTop",baseDto.getAsString("orgName"));
        baseDto.put("orgNameBottom",baseDto.getAsString("orgName")+"住院部");
        map.putAll(baseDto);
        String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/prepaidPaymentPrint.jasper", map, null, "prepaidPaymentPrint");
        return  printPath;
    }

	/**
	 * 获取预交金清单打印路径
	 * @param patPrepayment
	 * @return
	 * @author CTQ
	 */

	public String detailedListPrint(PatPrepayment patPrepayment){
		User user = UserUtils.getUser();
		Map map = new HashMap();
		List<BaseDto> baseDtos = dao.searchWaitPrePayment(patPrepayment);
		if(baseDtos!=null && baseDtos.size()>0){
			map.putAll(baseDtos.get(0));
		}
		String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/detailedListPrint.jasper", map, null, "detailedListPrint");
		return  printPath;
	}

	/**
	 * 预交金结账打印
	 * @param inpAcctMaster
	 * @return
	 * @author 赵宁
	 */
	public String prepaymentCheckPrint(InpAcctMaster inpAcctMaster){
        String printPath="";
		User user=UserUtils.getUser();
		inpAcctMaster.setCreateBy(user);
		inpAcctMaster.setOrgId(user.getOrgId());
		Map map=new HashMap();
		map.put("operator",user.getName());
		map.put("transact_date",DateUtils.getDateTime());
		map.put("acctNo",inpAcctMaster.getAcctNo());
        BaseDto baseDto=dao.printPrepayAcct(inpAcctMaster);
        map.put("rcpt_num",baseDto.get("rcpt_num"));
		map.put("sum_amount",baseDto.get("sum_amount"));
		map.put("invalid_num",baseDto.get("invalid_num"));
		map.put("invalid_amount",baseDto.get("invalid_amount"));
		map.put("refund_num",baseDto.get("refund_num"));
		map.put("refund_amount",baseDto.get("refund_amount"));
        map.put("minrcptno",baseDto.get("min_rcpt_no"));
		map.put("maxrcptno",baseDto.get("max_rcpt_no"));
		map.put("print_date", DateUtils.getDateTime());
		map.put("total",baseDto.get("total"));
		BigDecimal total=(BigDecimal)baseDto.get("total");
		String s = NumberToCN.number2CNMontrayUnit(total);
		map.put("uptotal",s.toString());
        List<BaseDto> list= dao.printGetPayWay(inpAcctMaster);
		printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/prepaymentCheckPrint.jasper", map, list, "prepaymentCheckPrint");
		return printPath;
	}
}